package com.xuecheng.system.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.dto.LoginDto;
import com.xuecheng.commons.model.vo.LoginVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.JwtUtils;
import com.xuecheng.system.domain.User;
import com.xuecheng.system.mappers.UserMapper;
import com.xuecheng.system.service.UserService;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public ResponseResult login(LoginDto param) {
        //获取输入过来的值
        //手机号
        String phone = param.getUsername();
        String password = param.getPassword();//密码
        String utype = param.getUtype();//类型
        //判断传过来的值是不是空值
        if (StringUtils.isEmpty(phone)||StringUtils.isEmpty(password) ||StringUtils.isEmpty(utype)) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }
        //根据手机号和utype查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone,phone);
        wrapper.eq(User::getUtype,utype);
        User user = this.getOne(wrapper);
        //判断是不是空
        if (user==null) {
            throw new BusinessException(ErrorCode.MEDIABINDERROR);
        }
        //判断密码是否一致
        //首先对用户输入的密码加密
        password= DigestUtil.md5Hex(password);
        if (!password.equals(user.getPassword())) {
            throw new BusinessException(ErrorCode.LOGINERROR);
        }

        //一致生成token
        Map map=new HashMap();
        map.put("userId",user.getId());
        map.put("companyId",user.getCompanyId());
        map.put("companyName",user.getCompanyName());
        String token = JwtUtils.createToken(map, 30);//存入token的数据超时时间30分钟

        //构造返回
        LoginVo loginVo = new LoginVo();
        loginVo.setAccess_token(token);
        loginVo.setUsername(user.getName());
        return ResponseResult.okResult(loginVo);
    }
}
